<?php
//header('Content-type: text/plain; charset=utf-8');

// Montrer les erreurs
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);


// includes
include_once '../model/config.php';
include_once 'ProjetManager.php';
include_once 'SeanceManager.php';
include_once 'ClasseManager.php';
include_once 'ExamenManager.php';

require_once "../libs/Ical/class.php";

if (!isset($_POST['req'])){
    die("no request");
}
else {
    //URL - ICAL
    if ($_POST['req'] == "URL"){
        $json = array("success"=>false,"msg"=>"","req"=>"URL");
        $html ="";
        $html .="<form id=\"ajaxGroupBEForm\" method='post' >";
        $html .= "<fieldset id=\"listeSeance\" data-role=\"controlgroup\">";
        //$html .= "<legend>Liste des BEs:</legend>";                            
        $export = new ICalExporter();
        //$urlTest="https://srv-ade.insa-toulouse.fr/jsp/custom/modules/plannings/anonymous_cal.jsp?resources=431,438&projectId=4&calType=ical&firstDate=2014-08-04&lastDate=2015-07-31";
        //$ical = file_get_contents("../Icalfiles/ADECal.ics");
        $urlTest=$_POST['data'];
        $ical = file_get_contents($urlTest);
        $events = $export->toHash($export->toIcalfromString($ical));

        //Lister les BEs
        if ( $_POST['type']){
            foreach ($events as $key=>$value) {
                switch ($_POST['type']) {
                    case 'Projet':
                        $clé="BE ";
                                                   
                        if (stristr($value['text'],$clé) !== FALSE){
                            $idBE=$value['text'];
                            $location=$value['location'];
                            $date=$value['start_date'];
                            $name=explode(" ",$value['text']);
                            $BE = "";

                            //find the last key of the array
                            end($name);
                            $last_key = key($name);

                            foreach ($name as $key => $value) {
                                if ($key != $last_key){
                                    $BE .= $value."_";
                                }
                                else {
                                    $BE .= $value;
                                }
                            }

                            $html .="<label for=\"".$BE."\">".$idBE."</label>";
                            $html .="<label for=\"".$BE."\" id=\"location".$BE."\" >".$location."</label>";
                            $html .="<label for=\"".$BE."\" id=\"date".$BE."\">".$date."</label>";
                            $html .="<input type=\"checkbox\" name=\"seanceBE[]\" id=\"".$BE."\" value=\"".$idBE."\">";
                        }
                        
                        
                        break;
                    case 'Examen':
                        $clé=array("Examen","Exam","Controle","Contrôle","Evaluation","Soutenance");
                                                      
                        if ((stristr($value['text'],$clé[0]) !== FALSE) || (stristr($value['text'],$clé[1]) !== FALSE) || (stristr($value['text'],$clé[2]) !== FALSE)
                                || (stristr($value['text'],$clé[3]) !== FALSE) || (stristr($value['text'],$clé[4]) !== FALSE) || (stristr($value['text'],$clé[5]) !== FALSE)){
                            $idBE=$value['text'];
                            $location=$value['location'];
                            $date=$value['start_date'];
                            $name=explode(" ",$value['text']);
                            $BE = "";

                            //find the last key of the array
                            end($name);
                            $last_key = key($name);

                            foreach ($name as $key => $value) {
                                if ($key != $last_key){
                                    $BE .= $value."_";
                                }
                                else {
                                    $BE .= $value;
                                }
                            }

                            $html .="<label for=\"".$BE."\">".$idBE."</label>";
                            $html .="<label for=\"".$BE."\" id=\"location".$BE."\" >".$location."</label>";
                            $html .="<label for=\"".$BE."\" id=\"date".$BE."\">".$date."</label>";
                            $html .="<input type=\"checkbox\" name=\"seanceBE[]\" id=\"".$BE."\" value=\"".$idBE."\">";
                        }

                        break;
                    default:
                        echo "No type";
                        break;
                }

           }
           $html .="</fieldset>";
           $html .="<input type=\"submit\" data-theme=\"e\" data-inline=\"true\" name=\"submitSelectBE\" id=\"submitSelectBE\" value=\"Creer un Projet/Examen\" data-icon=\"plus\" data-iconpos=\"left\">";
           $html .="</form>";
           $json['success']=true;
           $json['msg']=utf8_encode(iconv("UTF-8", "ISO-8859-1", $html));
           //$json['msg']=iconv("UTF-8", "ISO-8859-1", $html);
           //$json['msg']=mb_convert_encoding($html, "utf8");

           print(json_encode($json));
        }
        else{
                       
           $json['success']=false;
           $json['msg']="No categorie";

           print(json_encode($json));
        }
                                    
    }
    
    //Ajouter un BE
    elseif ($_POST['req'] == "newProjet"){ 
        $json = array("success"=>false,"msg"=>"","msg2"=>"","req"=>"newProjet");
        
        ///UNCHECKED SEANCES
        $uncheck=$_POST['data'][1];
        //uncheck non vide
        if ($uncheck != "no uncheck"){
            $html ="";
            $html .="<form id=\"ajaxGroupBEForm\" method=\"post\" >";
            $html .= "<fieldset id=\"listeSeance\" data-role=\"controlgroup\">";
            foreach ($uncheck as $value) {
                    $html .="<label for=\"".$value[0]."\">".$value[0]."</label>";
                    $html .="<label for=\"".$value[0]."\" id=\"location".$value[0]."\">".$value[1]."</label>";
                    $html .="<label for=\"".$value[0]."\" id=\"date".$value[0]."\">".$value[2]."</label>";
                    $html .="<input type=\"checkbox\" name=\"seanceBE[]\" id=\"".$value[0]."\" value=\"".$value[0]."\">";
            }
            $html .="</fieldset>";
            $html .="<input type=\"submit\" data-theme=\"e\" data-inline=\"true\" name=\"submitSelectBE\" id=\"submitSelectBE\" value=\"Creer un Projet/Examen\" data-icon=\"plus\" data-iconpos=\"left\">";
            $html .="</form>";
        }
        //uncheck vide
        else {
            $html ="";
            $html .="<form id=\"ajaxGroupBEForm\" method=\"post\" >";
            $html .= "<fieldset data-role=\"controlgroup\">";
            $html .="</fieldset>";
            $html .="<input type=\"submit\" data-theme=\"e\" data-inline=\"true\" name=\"submitSelectBE\" id=\"submitSelectBE\" value=\"Creer un Projet/Examen\" data-icon=\"plus\" data-iconpos=\"left\">";
            $html .="</form>";
        }
        
        //CHECKED SEANCES
        $html2="";
        $check =$_POST['data'][0];
        if ($check != "no check"){
            $name=explode(" ",$check[0][0]);
            //find the last key of the array
            end($name);
            $last_key = key($name);
            $projet="";
            for ($i=0;$i<2;$i++){
                if ($i != $last_key){
                    $projet .=$name[$i]." ";
                }
            }
            //Id du BE choisie dans la liste des BEs choisies
            $idBeChoisie=$_POST['data'][2];
            
            $html2 .="<div id=\"".$projet.$idBeChoisie."\" data-role=\"collapsible\" data-theme=\"e\">";
            $html2 .="<h3>Categorie".$idBeChoisie."</h3>";
            $html2 .="<label for=\"name-BE".$idBeChoisie."\" ><h3>Title:</h3></label>";
            $html2 .="<input type=\"text\" name=\"name-BE".$idBeChoisie."\" id=\"name-BE".$idBeChoisie."\" value=\"".$projet."\" data-clear-btn=\"true\">";
            $html2 .="<label for=\"BE".$idBeChoisie."\" ><h3>Seances:</h3></label>";
            $html2 .="<div id=\"BE".$idBeChoisie."\">";
            
            foreach ($check as $value) {
                    $html2 .="<button id=\"BE".$idBeChoisie.";".$value[0].";".$value[1].";".$value[2]."\" name=\"seanceButton\" class=\"ui-btn ui-corner-all ui-icon-delete ui-btn-icon-right\">" .$value[0]."</button>";
                }                
            $html2 .="</div>";
           
            $html2 .="<a id=\"delete-".$projet."-".$idBeChoisie."\" name=\"supprimerBE\" class=\"ui-btn ui-btn-d ui-btn-inline ui-corner-all ui-icon-delete ui-btn-icon-right\">supprimer BE/Examen</a>";
            $html2 .="</div>";
            
        }

        //MIS A JOUR DE LA PAGE
        $json['success']=true;
        //$json['msg']=utf8_encode($html);
        $json['msg']=utf8_encode(iconv("UTF-8", "ISO-8859-1", $html));
        //$json['msg2']=utf8_encode($html2);
        $json['msg2']=utf8_encode(iconv("UTF-8", "ISO-8859-1", $html2));

        print(json_encode($json));

    }
    else if ($_POST['req'] == "modifyProjet"){
        $json = array("success"=>false,"msg"=>"","req"=>"modifyProjet");
        
        $infoSeance =explode(";",$_POST['data']);
        
        $html ="";
                            
        $html .="<label for=\"".$infoSeance[1]."\">".$infoSeance[1]."</label>";           
        $html .="<label for=\"".$infoSeance[1]."\" id=\"location".$infoSeance[1]."\">".$infoSeance[2]."</label>";            
        $html .="<label for=\"".$infoSeance[1]."\" id=\"date".$infoSeance[1]."\">".$infoSeance[3]."</label>";
        $html .="<input type=\"checkbox\" name=\"seanceBE[]\" id=\"".$infoSeance[1]."\" value=\"".$infoSeance[1]."\">";
        
        $json['success']=true;
        //$json['msg']=utf8_encode($html);
        $json['msg']=utf8_encode(iconv("UTF-8", "ISO-8859-1", $html));
        print(json_encode($json));
    }
    else if ($_POST['req'] == "deleteProjet"){
        $json = array("success"=>false,"msg"=>"","req"=>"deleteProjet");
        $seances=$_POST['data'];
        
        $html ="";
        foreach ($seances as $value) {
            $infoSeance=explode(";",$value);
            $html .="<label for=\"".$infoSeance[1]."\">".$infoSeance[1]."</label>";           
            $html .="<label for=\"".$infoSeance[1]."\" id=\"location".$infoSeance[1]."\">".$infoSeance[2]."</label>";            
            $html .="<label for=\"".$infoSeance[1]."\" id=\"date".$infoSeance[1]."\">".$infoSeance[3]."</label>";
            $html .="<input type=\"checkbox\" name=\"seanceBE[]\" id=\"".$infoSeance[1]."\" value=\"".$infoSeance[1]."\">";
        }
                
        $json['success']=true;
        //$json['msg']=utf8_encode($html);
        $json['msg']=utf8_encode(iconv("UTF-8", "ISO-8859-1", $html));
        print(json_encode($json));
        
    }
    else if ($_POST['req'] == "valideProjet"){
        $json = array("success"=>false,"msg"=>"","req"=>"valideProjet");
                
        $managerProjet = new ProjetManager($bdd);
        $managerSeance = new SeanceManager($bdd);
        $managerClasse = new ClasseManager($bdd);
        //info Class
        $class =$_POST['data'][0];
        
        //info BE
        $totalBE =$_POST['data'][1];
        
        $idNewBE=1;
        
        foreach ($totalBE as $elemBE){
            //Nom du BE
            $nameBE= $elemBE[0];
            
            //info seances
            $totalSeance= $elemBE[1];
            //$idNewSeance=1;
            foreach ($totalSeance as $elemSeance) {
                $elm =explode(";",$elemSeance);
                $newSeance = new Seance($elm[1]." - ".$elm[2], 1, $idNewBE, $elm[3]);
                //$idNewSeance++;
                $sortSeance[]=$elm[3];
                $listeNewSeance[]=$newSeance;
               
            }
            sort($sortSeance);
            $debutProjet=$sortSeance[0];
            end($sortSeance);
            $finProjet=$sortSeance[key($sortSeance)];
            
            //Ajouter le projet dans la BDD
            
            //Recherche de l'id de la classe
            $find1=$managerClasse->getListClasse();
            foreach ($find1 as $value) {
                if ($value->getLibelleClasse() == $class){
                    $idClass=$value->getIdClasse();
                    break;
                }
            }
            $newProjet = new Projet($idNewBE, $nameBE, $debutProjet, $finProjet, 1, $idClass);
            $managerProjet->add($newProjet);
            
            //Ajouter les seances dans le BDD
            
            //Recherche de l'id du projet
            //$idProjetBDD=$managerProjet->findIdProjetByLibelle($nameBE);
            $find1=$managerProjet->getListProjetParClass($idClass);
            foreach ($find1 as $value1) {
                if ($value1->getLibelleProjet() == $nameBE){
                    $idProjetBDD=$value1->getIdProjet();
                    break;
                }
            }

            foreach ($listeNewSeance as $value2){
                $value2->setIdProjet($idProjetBDD);
                $managerSeance->add($value2);
            }
            $idNewBE++;
        }

        
        /*
        $newProjet = new Projet(1, $projet, "", "", 1, 1);
        $newProjet = new Projet($idProjet, $libelleProjet, $debutProjet, $finProjet, $idCategorie, $idClasse);
        $newSeance = new Seance($libelleSeance, $idSeance, $idProjet, $dateSeance);
        $managerProjet->add($newBE);
        */
                
        $json['success']=true;
        $json['msg']="BE dans BDD";
        print(json_encode($json));
    }
        
    else if ($_POST['req'] == "valideExamen"){
        $json = array("success"=>false,"msg"=>"","req"=>"valideExamen");
                
        $managerExamen = new ExamenManager($bdd);
        $managerClasse = new ClasseManager($bdd);
        //info Class
        $class =$_POST['data'][0];
        
        //info BE
        $totalExamen =$_POST['data'][1];
        $idNewExamen=1;
        
        foreach ($totalExamen as $elemExam){
            //Nom du BE
            $nameExamen= $elemExam[0];
            
            //info seances
            $elm =explode(";",$elemExam[1]);
            $date=$elm[3];
    
            //Ajouter l'examen dans la BDD
            
            //Recherche de l'id de la classe
            $find1=$managerClasse->getListClasse();
            foreach ($find1 as $value) {
                if ($value->getLibelleClasse() == $class){
                    $idClass=$value->getIdClasse();
                    break;
                }
            }
            
            $newExam = new Examen($idNewExamen, 2, $idClass, $date, $nameExamen);
            $managerExamen->add($newExam);
            $idNewExamen++;
        }
                
        $json['success']=true;
        $json['msg']="Examens dans BDD";
        print(json_encode($json));
    }
}
                                                       
    
?>
